package org.jeecg.controller;

import lombok.Cleanup;
import org.jeecg.filter.FileTypeFilter;
import org.jeecg.result.ResultTool;
import org.jeecg.util.CommonUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
public class CommonController {

    /**
     * 文件上传统一方法
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/upload")
    public ResultTool<?> upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ResultTool<?> result = new ResultTool<>();
        String savePath = "";
        String bizPath = request.getParameter("biz");

        //LOWCOD-2580 sys/common/upload接口存在任意文件上传漏洞
        if (bizPath != null) {
            if (!bizPath.equals("")){
                if(bizPath.contains("../") || bizPath.contains("..\\")){
                    throw new Exception("上传目录bizPath，格式非法！");
                }
            }
        }else {
            bizPath = "";
        }


        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获取上传文件对象
        MultipartFile file = multipartRequest.getFile("file");




        //update-begin-author:liusq date:20221102 for: 过滤上传文件类型
        FileTypeFilter.fileTypeFilter(file);
        //update-end-author:liusq date:20221102 for: 过滤上传文件类型
        //update-begin-author:lvdandan date:20200928 for:修改JEditor编辑器本地上传
        savePath = this.uploadLocal(file,bizPath);
        //update-begin-author:lvdandan date:20200928 for:修改JEditor编辑器本地上传
        /**  富文本编辑器及markdown本地上传时，采用返回链接方式
         //针对jeditor编辑器如何使 lcaol模式，采用 base64格式存储
         String jeditor = request.getParameter("jeditor");
         if(oConvertUtils.isNotEmpty(jeditor)){
         result.setMessage(CommonConstant.UPLOAD_TYPE_LOCAL);
         result.setSuccess(true);
         return result;
         }else{
         savePath = this.uploadLocal(file,bizPath);
         }
         */



        if(savePath != null || !savePath.equals("")){
            result.setMessage(savePath);
            result.setStatus(200);
        }else {
            result.setMessage("上传失败！");
            result.setStatus(400);
        }
        return result;
    }



    /**
     * 本地文件上传
     * @param mf 文件
     * @param bizPath  自定义路径
     * @return
     */
    private String uploadLocal(MultipartFile mf,String bizPath){
        InputStream inputStream = null;
        try {
            String ctxPath = "D/temp/upFiles";
            String fileName = null;
            File file = new File(ctxPath + File.separator + bizPath + File.separator );
            if (!file.exists()) {
                // 创建文件根目录
                file.mkdirs();
            }
            // 获取文件名
            String orgName = mf.getOriginalFilename();
            orgName = CommonUtils.getFileName(orgName);
            if(orgName.indexOf(".")!=-1){
                fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."));
            }else{
                fileName = orgName+ "_" + System.currentTimeMillis();
            }
            String savePath = file.getPath() + File.separator + fileName;
            File savefile = new File(savePath);

            FileOutputStream os = new FileOutputStream(savefile.getAbsolutePath());

//            FileCopyUtils.copy(mf.getBytes(), savefile);
            inputStream = mf.getInputStream();
            FileCopyUtils.copy(inputStream,os);



            String dbpath = null;
            if(bizPath != null || !bizPath.equals("")){
                dbpath = bizPath + File.separator + fileName;
            }else{
                dbpath = fileName;
            }
            if (dbpath.contains("\\")) {
                dbpath = dbpath.replace("\\", "/");
            }
            return dbpath;
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return "";
    }











}
